package com.example.mq.config.mq;

import com.alibaba.fastjson.JSONObject;
import com.example.mq.config.es.ElasticService;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @site http://zouyujie.top
 * @date 2022/3/14 22:49
 */
@Component
public class MqConsumerService implements MessageListenerConcurrently{

    private static final Logger logger = LoggerFactory.getLogger(MqConsumerService.class);

    @Autowired
    ElasticService elasticService;

    @Value("${es.indices}")
    private String indices;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt messageExt : list) {
            try {
                if (elasticService.exists(indices)) {
                    doMessageExt(messageExt);
                }else{
                    if(elasticService.create()){
                        doMessageExt(messageExt);
                    }else{
                        logger.error("索引创建失败");
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    private void doMessageExt(MessageExt messageExt) throws IOException {
        RestStatus restStatus = elasticService.insertDoc(messageExt.getTopic(), messageExt.getMsgId(), JSONObject.toJSONString(messageExt));
        if(Objects.equals(restStatus, RestStatus.OK) || Objects.equals(restStatus, RestStatus.CREATED)){

            logger.info(messageExt.getMsgId()+"加入文档");

        }else{
            logger.error(messageExt.getMsgId()+"加入文档失败");
        }
    }
}
